var http = require('http');
var Promise = require('Promise');
var cheerio = require('cheerio');

var baseUrl = "http://www.imooc.com/learn/";
console.log(baseUrl);
var url = "http://www.imooc.com/learn/637";
console.log(url);
var vedioIds = [348, 259, 197, 134, 75];

function getPageAsync(url) {
	return Promise(function (resolve, reject) {
		console.log('正在爬去.....' + url);

		http.get(url, function (res) {
			var html = '';

			res.on('data', function (data) {
				html += data;
			})

			res.on('end', function () {
				// console.log(html);
				resolve(html);
				// var courdata=filterChap(html);
				// printdata(courdata);
			})
		}).on('error', function (e) {
			reject(e);
			console.log('出错');
		});
	})
}

function filterChap(html) {
	var $ = cheerio.load(html);
	var chapts = $('.mod-chapters');
	var title = $('#main > div.course-infos > div.w.pr > div.hd.clearfix > h2').text();
	var number = $('#main > div.course-infos > div.w.pr > div.statics.clearfix > div:nth-child(3) > span.meta-value.js-learn-num').text().trim();
	number = parseInt(number, 10);
	var courdata = {
		vedios: [],
		title: title,
		number: number,
	};
	chapts.each(function (item) {
		var chapt = $(this);
		var chapttitle = chapt.find('strong').text();
		var vedios = chapt.find('.vedio').children('li');

		var chaptdata = {
			chapttitle: chapttitle,
			vedios: []
		}
		vedios.each(function (item) {
			var vedio = $(this).find('.J-media-item');
			var vediotitle = vedio.text();
			var id = vedio.attr('href').split('vedio/')[1];

			chaptdata.vedios.push({
				title: vediotitle,
				id: id
			})
		})

		courdata.push(chaptdata);
	})
	return courdata;
}

function printdata(courdata) {
	courdata.sort(function (a, b) {

	})

	console.log(courdata);
	courdata.forEach(item => {
		var number = item.number;
		var chapttitle = item.chapttitle;
		console.log(number + '------' + item.title);

		item.vedios.forEach(vedio => {
			console.log('  [' + vedio.id + ']:' + vedio.title);
		})
	});
}

var fetchCourseArray = [];

vediosIds.forEach(function (id) {
	fetchCourseArray.push(getPageAsync(baseUrl + id));
})

Promise.all(fetchCourseArray)
	.then(function (pages) {
		var courseData = [];
		pages.forEach(function (html) {
			var courses = filterChap(html);
			courseData.push(courses);
		})

		printdata(courseData);
	})
